<?php

// +----------------------------------------------------------------------
// | Description: 公共控制器，公用方法
// | Author:      李大明
// | Email:       limingnk@qq.com
// | DateTime:    2016-07-20 16:22:22
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Think\Controller;

class PublicController extends Controller {

	public $weObj = NULL;

	public function __construct() {
		parent::__construct();
		//引入企业号SDK
		Vendor('Weixin.qywechat');
		$options = array(
			'token' => C('TOKEN'), //填写应用接口的Token
			'encodingaeskey' => C('ENCODINGAESKEY'), //填写加密用的EncodingAESKey
			'appid' => C('CORPID'), //填写高级调用功能的app id
			'appsecret' => C('CORPSECRET'), //填写高级调用功能的密钥
			'agentid' => C('AGENTID'), //应用的id
			'debug' => ture, //调试开关
			'logcallback' => 'logg', //调试输出方法，需要有一个string类型的参数
		);
		$this->weObj = new \Wechat($options);
	}

	public function callBack() {

		$encodingAesKey = C('ENCODINGAESKEY');
		$token = C('TOKEN');
		$corpId = C('CORPID');

		//1.解析出Get请求的参数，包括消息体签名(msg_signature)，时间戳(timestamp)，随机数字串(nonce)以及公众平台推送过来的随机加密字符串(echostr),这一步注意作URL解码。
		//2.验证消息体签名的正确性
		//3. 解密出echostr原文，将原文当作Get请求的response，返回给公众平台
		//第2，3步可以用公众平台提供的库函数VerifyURL来实现。

		$sVerifyMsgSig = urldecode($_GET['msg_signature']);
		$sVerifyTimeStamp = urldecode($_GET['timestamp']);
		$sVerifyNonce = urldecode($_GET['nonce']);
		$sVerifyEchoStr = urldecode($_GET['echostr']);

		// 需要返回的明文
		$sEchoStr = "";
		Vendor('Weixin.WXBizMsgCrypt');
		$wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
		$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
		if ($errCode == 0) {
			// 验证URL成功，将sEchoStr返回
			echo $sEchoStr;
		} else {
			print("ERR: " . $errCode . "\n\n");
		}
	}

	public function getUserIdInCookie() {
		$userid = cookie('userid');
		if (!$userid) {
			$callback = "zhihui.yeethink.com/index.php/Admin/Public/getUserIdByCode";
			$url = $this->weObj->getOauthRedirect($callback);
			redirect($url);
		} else {
			return $userid;
		}
	}

	public function getUserIdByCode() {
		$code = I('code');
		$data = $this->weObj->getUserId($code, C('AGENTID'));
		cookie('userid', $data['UserId']);
		redirect(U('index'));
	}
}